# utils/verification_code.py


from tools.myredis import mredis

import random


from django.conf import settings


class VerificationUtils:
    @staticmethod
    def generate_verification_code(length=4):
        """生成指定长度的数字验证码"""
        return ''.join(random.choices('0123456789', k=length))

    @staticmethod
    def get_code_key(phone):
        """获取图像验证码存储key"""
        return f"verify_code:{phone}"

    @staticmethod
    def get_interval_key(phone):
        """获取发送间隔key"""
        return f"verify_interval:{phone}"

    @staticmethod
    def save_verification_code(phone, code):
        """保存验证码到Redis"""
        code_key = VerificationUtils.get_code_key(phone)
        # 保存5分钟
        mredis.setex(code_key, 300, code)
        return True

    @staticmethod
    def get_verification_code(phone):
        """获取验证码"""
        code_key = VerificationUtils.get_code_key(phone)
        return mredis.get(code_key)

    @staticmethod
    def check_send_interval(phone):
        """检查发送间隔（1分钟内只能发一次）"""
        interval_key = VerificationUtils.get_interval_key(phone)
        return mredis.exists(interval_key)

    @staticmethod
    def set_send_interval(phone):
        """设置发送间隔（1分钟）"""
        interval_key = VerificationUtils.get_interval_key(phone)
        mredis.setex(interval_key, 60, "1")
        return True

    @staticmethod
    def verify_code(phone, input_code):
        """验证验证码"""
        stored_code = VerificationUtils.get_verification_code(phone)
        return stored_code and stored_code == input_code

    @staticmethod
    def delete_verification_code(phone):
        """删除验证码"""
        code_key = VerificationUtils.get_code_key(phone)
        return mredis.delete(code_key)


verification_utils = VerificationUtils()


# def generate_verification_code(length=6):
#     """生成指定长度的数字验证码"""
#     return ''.join(random.choices('0123456789', k=length))
#
#
# def save_verification_code(phone, code):
#     """保存验证码到缓存"""
#     expiration_time = settings.VERIFICATION_CODE['EXPIRATION_TIME']
#     cache_key = f'verification_code:{phone}'
#     mredis.setex(cache_key, code, expiration_time)
#
#     # 设置发送间隔标记
#     interval_key = f'verification_code_interval:{phone}'
#     cache.set(interval_key, True, settings.VERIFICATION_CODE['SEND_INTERVAL'])
#
#
# def check_send_interval(phone):
#     """检查发送间隔"""
#     interval_key = f'verification_code_interval:{phone}'
#     return cache.get(interval_key) is not None
#
#
# def get_verification_code(phone):
#     """获取验证码"""
#     cache_key = f'verification_code:{phone}'
#     return mredis.get(cache_key)
#
#
# def delete_verification_code(phone):
#     """删除验证码"""
#     cache_key = f'verification_code:{phone}'
#     mredis.delete(cache_key)